package com.bfonseca.pedreiropic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class MainActivity extends Activity {
	private int CAMERA_PIC_REQUEST = 2;
	private int GALLERY_PIC_REQUEST = 3;

	private int TAKE_PICTURE = 0;
//
	static int MAX_IMAGE_DIMENSION = 0;

	ImageView imageV;
	ImageView dizerV;
	ImageView acessorios;
	private int ax = 0, ay = 0;
	private int ascale = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		MAX_IMAGE_DIMENSION = metrics.widthPixels;
		Intent cameraIntent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

		acessorios = (ImageView) findViewById(R.id.acessorios);

		try {

			acessorios.setImageBitmap(getBitmapCap());

		} catch (Exception e) {
			e.printStackTrace();
		}

		acessorios.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				onToucheEvent(event);
				return true;
			}
		});
	}

	private Bitmap getBitmapCap() {
		Bitmap retorno = null;
		try {
			AssetManager assetManager = getAssets();

			InputStream istr;

			istr = assetManager.open("capacete.png");

			Bitmap bmpCap = BitmapFactory.decodeStream(istr);
			Config conf = Bitmap.Config.ARGB_8888; // see other conf type

			DisplayMetrics metrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(metrics);

			retorno = Bitmap.createBitmap(metrics.widthPixels,
					metrics.heightPixels, conf);

			Canvas cc = new Canvas(retorno);
			Matrix matrix = new Matrix();
			matrix.setScale(ascale, ascale);
			cc.setMatrix(matrix);
			// cc.drawBitmap(bmpCap, matrix, null);

			cc.drawBitmap(bmpCap, ax / 2, ay / 2, null);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return retorno;
	}

	// events when touching the screen
	public boolean onToucheEvent(MotionEvent event) {
		int eventaction = event.getAction();

		int X = (int) event.getX();
		int Y = (int) event.getY();

		switch (eventaction) {

		case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on
										// a ball
			// for (ColorBall ball : colorballs) {
			// check all the bounds of the ball
			// if (X > ball.getX() && X < ball.getX()+50 && Y > ball.getY() && Y
			// < ball.getY()+50){
			// balID = ball.getID();
			// break;
			// }
			// }

			break;

		case MotionEvent.ACTION_MOVE: // touch drag with the ball
			// move the balls the same as the finger
			ax = (X - 25);
			ay = (Y - 25);

			break;

		case MotionEvent.ACTION_UP:
			// touch drop - just do things here after dropping

			break;
		}
		acessorios.setImageBitmap(getBitmapCap());
		return true;

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bitmap thumbnail = null;

		try {
			if (requestCode == CAMERA_PIC_REQUEST) {

				thumbnail = (Bitmap) data.getExtras().get("data");

			} else if (requestCode == GALLERY_PIC_REQUEST) {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String filePath = cursor.getString(columnIndex);
				cursor.close();

				// thumbnail = BitmapFactory.decodeFile(filePath);

				InputStream imageStream = getContentResolver().openInputStream(
						selectedImage);
				thumbnail = getCorrectlyOrientedImage(this, selectedImage);

				// thumbnail = BitmapFactory.decodeStream(imageStream);

				// thumbnail = loadBitmap(selectedImage);

			} else {
				// Toast.makeText(MainActivity.this, "Picture NOt taken",
				// Toast.LENGTH_LONG).show();
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				startActivityForResult(intent, GALLERY_PIC_REQUEST);
			}
		} catch (Exception e) {
			// Toast.makeText(MainActivity.this, "Picture NOt taken",
			// Toast.LENGTH_LONG).show();
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
			startActivityForResult(intent, GALLERY_PIC_REQUEST);
			e.printStackTrace();
		}
		if (thumbnail != null) {
			imageV = (ImageView) findViewById(R.id.imagem);
			imageV.setImageBitmap(thumbnail);

			dizerV = (ImageView) findViewById(R.id.dizer);
			dizerV.setImageBitmap(processaPicture());
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {

			BitmapDrawable drawable = (BitmapDrawable) imageV.getDrawable();
			Bitmap bmpImagBitmap = drawable.getBitmap();

			drawable = (BitmapDrawable) dizerV.getDrawable();
			Bitmap bmpDizer = drawable.getBitmap();

			drawable = (BitmapDrawable) acessorios.getDrawable();
			Bitmap bmpAcessorio = drawable.getBitmap();

			Canvas c = new Canvas(bmpImagBitmap);
			c.drawBitmap(bmpAcessorio, 0, 0, null);
			c.drawBitmap(bmpDizer, 0, 0, null);

			String path = Environment.getExternalStorageDirectory().toString();
			OutputStream fOut = null;
			File file = new File(path, "FitnessGirl.jpg");
			fOut = new FileOutputStream(file);

			bmpImagBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
			fOut.flush();
			fOut.close();

			MediaStore.Images.Media.insertImage(getContentResolver(),
					file.getAbsolutePath(), file.getName(), file.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri)
			throws IOException {
		InputStream is = context.getContentResolver().openInputStream(photoUri);
		BitmapFactory.Options dbo = new BitmapFactory.Options();
		dbo.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(is, null, dbo);
		is.close();

		int rotatedWidth, rotatedHeight;
		int orientation = getOrientation(context, photoUri);

		if (orientation == 90 || orientation == 270) {
			rotatedWidth = dbo.outHeight;
			rotatedHeight = dbo.outWidth;
		} else {
			rotatedWidth = dbo.outWidth;
			rotatedHeight = dbo.outHeight;
		}

		Bitmap srcBitmap;
		is = context.getContentResolver().openInputStream(photoUri);
		if (rotatedWidth > MAX_IMAGE_DIMENSION
				|| rotatedHeight > MAX_IMAGE_DIMENSION) {
			float widthRatio = ((float) rotatedWidth)
					/ ((float) MAX_IMAGE_DIMENSION);
			float heightRatio = ((float) rotatedHeight)
					/ ((float) MAX_IMAGE_DIMENSION);
			float maxRatio = Math.max(widthRatio, heightRatio);

			// Create the bitmap from file
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = (int) maxRatio;
			srcBitmap = BitmapFactory.decodeStream(is, null, options);
		} else {
			srcBitmap = BitmapFactory.decodeStream(is);
		}
		is.close();

		/*
		 * if the orientation is not 0 (or -1, which means we don't know), we
		 * have to do a rotation.
		 */
		if (orientation > 0) {
			Matrix matrix = new Matrix();
			matrix.postRotate(orientation);

			srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
					srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
		}

		return srcBitmap;
	}

	private Bitmap processaPicture() {
		// Config cfg =
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);

		Config conf = Bitmap.Config.ARGB_8888; // see other conf types

		Bitmap bmp = Bitmap.createBitmap(metrics.widthPixels,
				metrics.heightPixels, conf); // this
		// creates
		// a
		// MUTABLE
		// bitmap
		// Canvas canvasss = new Canvas(bmp);
		// canvasss.drawBitmap(pic);
		// return bmp;

		// Canvas canvas = new Canvas(bmp);

		// Bitmap retorno = Bitmap.createBitmap(pic.getWidth(), pic.getHeight(),
		// Bitmap.Config.ARGB_8888);
		//
		// Canvas canvas = new Canvas();
		Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
		paint.setStyle(Paint.Style.FILL);
		paint.setColor(Color.BLACK);
		paint.setTextSize(15);
		paint.setAntiAlias(true);
		paint.setTypeface(Typeface.DEFAULT);
		paint.setShadowLayer(1, 1, 1, Color.WHITE);
		//
		// canvas.setBitmap(pic);
		// canvas.drawText("Ui adoro", 100, 100, paint);
		//
		Canvas singleUseCanvas = new Canvas();
		singleUseCanvas.setBitmap(bmp);
		// Matrix matrix = new Matrix();
		// matrix.postRotate(90,pic.getWidth(),pic.getHeight());

		// singleUseCanvas.drawBitmap(pic, matrix,null);
		// singleUseCanvas.drawBitmap(pic, 0, 0, paint);
		String str = "Gata, me chama de\nfast food que eu te \ndou uma comidinha rápida,\nSUA LINDA!";
		int x = 8;
		int y = 20;
		Rect bounds = new Rect();
		Rect boundsTemp = new Rect();
		for (String line : str.split("\n")) {
			singleUseCanvas.drawText(line, x, y, paint);
			y += -paint.ascent() + paint.descent();
			paint.getTextBounds("Ui adoro", 0, "Ui adoro".length(), boundsTemp);
			bounds.set(0, 0, bounds.width() + boundsTemp.width(),
					bounds.height() + boundsTemp.height());

		}
		ImageView imgBalao = (ImageView) findViewById(R.id.balao);
		
		// LinearLayout.LayoutParams pars = new
		// LinearLayout.LayoutParams(bounds.width(),bounds.height());
		// imgBalao.setLayoutParams(new ViewGroup.LayoutParams(100, 100));

		// MarginLayoutParams marginParams = new
		// MarginLayoutParams(imgBalao.getLayoutParams());
		// marginParams.setMargins(0, 0, 0, 0);

		// RelativeLayout.LayoutParams layoutParams = new
		// RelativeLayout.LayoutParams(marginParams);

//		LinearLayout lin = (LinearLayout) findViewById(R.id.balaoFrame);
		// lin.setLayoutParams(new
		// LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
		// LayoutParams.FILL_PARENT));

//		lin.setLayoutParams(new RelativeLayout.LayoutParams(bounds.width(),
//				bounds.height()));
imgBalao.setScaleType(ScaleType.MATRIX);
Matrix mms = new Matrix();
imgBalao.setImageMatrix(mms);
imgBalao.setImageBitmap(get_ninepatch(R.drawable.btn_default, bounds.width(), bounds.height()*2, this));

		// imgBalao.setScaleType(ScaleType.FIT_START);

//		imgBalao.setMaxWidth(bounds.width());
//		imgBalao.setMinimumWidth(bounds.width());
//
//		imgBalao.setMaxHeight(bounds.height() * 2);
//		imgBalao.setMinimumHeight(bounds.height() * 2);

		// imgBalao.setLayoutParams(layoutParams);

		// imgBalao.setLayoutParams(pars);
		return bmp;
	}

	public static int getOrientation(Context context, Uri photoUri) {
		/* it's on the external media. */
		Cursor cursor = context.getContentResolver().query(photoUri,
				new String[] { MediaStore.Images.ImageColumns.ORIENTATION },
				null, null, null);

		if (cursor.getCount() != 1) {
			return -1;
		}

		cursor.moveToFirst();
		return cursor.getInt(0);
	}

	public Bitmap get_ninepatch(int id, int x, int y, Context context) {
		// id is a resource id for a valid ninepatch

		Bitmap bitmap = BitmapFactory
				.decodeResource(getResources(), R.drawable.btn_default_normal);

		byte[] chunk = bitmap.getNinePatchChunk();
//		NinePatchDrawable np = new NinePatchDrawable(bitmap, chunk, new Rect(), "");
		NinePatchDrawable np_drawable = new NinePatchDrawable(bitmap, chunk,
				new Rect(), null);
		np_drawable.setBounds(0, 0, x,y);

		Bitmap output_bitmap = Bitmap.createBitmap(x, y,
				Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(output_bitmap);
		np_drawable.draw(canvas);
		
		DisplayMetrics metrics = new DisplayMetrics();
		Config conf = Bitmap.Config.ARGB_8888; // see other conf type
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		Bitmap retorno = Bitmap.createBitmap(metrics.widthPixels,
				metrics.heightPixels, conf); 

		Canvas cc = new Canvas(retorno);
//		Matrix matrix = new Matrix();
//		matrix.setScale(ascale, ascale);
//		cc.setMatrix(matrix);
		// cc.drawBitmap(bmpCap, matrix, null);

		cc.drawBitmap(output_bitmap, 0, 0, null);
		
		return retorno;
	}
	// }
	// private Bitmap processaPicture(Bitmap pic){
	// Paint mPaint = new Paint();
	// //Canvas canvas = new Canvas();
	// //canvas.drawText("Canvas text", 10, 10, mPaint);
	// Canvas singleUseCanvas = new Canvas();
	// singleUseCanvas.setBitmap(pic);
	// singleUseCanvas.drawText("Bitmap text", 10, 30, mPaint);
	// return pic;
	// }

	// private Bitmap loadBitmap(Uri imageFileUri) {
	// Display currentDisplay = getWindowManager().getDefaultDisplay();
	//
	// float dw = currentDisplay.getWidth();
	// float dh = currentDisplay.getHeight();
	//
	// Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh,
	// Bitmap.Config.ARGB_4444);
	// try {
	// BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
	// bmpFactoryOptions.inJustDecodeBounds = true;
	// returnBmp = BitmapFactory.decodeStream(getContentResolver()
	// .openInputStream(imageFileUri), null, bmpFactoryOptions);
	// bmpFactoryOptions.inSampleSize = 2;
	// bmpFactoryOptions.inJustDecodeBounds = false;
	// returnBmp = BitmapFactory.decodeStream(getContentResolver()
	// .openInputStream(imageFileUri), null, bmpFactoryOptions);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return returnBmp;
	// }
}
